import Foundation
import Combine

class AuthManager: ObservableObject {
    @Published var currentUser: User?
    @Published var isAuthenticated = false
    @Published var authError: String?
    
    private let userDefaultsKey = "currentUser"
    
    init() {
        loadUserFromDefaults()
    }
    
    func login(email: String, password: String) {
        // 在实际应用中，这里应该调用API进行验证
        // 这里简化为模拟登录成功
        
        if email.isEmpty || password.isEmpty {
            self.authError = "邮箱和密码不能为空"
            return
        }
        
        // 模拟网络请求延迟
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            // 模拟登录成功
            let user = User(username: email.split(separator: "@").first?.description ?? "用户", email: email)
            self.currentUser = user
            self.isAuthenticated = true
            self.authError = nil
            
            // 保存用户信息到UserDefaults
            self.saveUserToDefaults(user)
        }
    }
    
    func register(username: String, email: String, password: String, confirmPassword: String) {
        // 在实际应用中，这里应该调用API进行注册
        // 这里简化为模拟注册成功
        
        if username.isEmpty || email.isEmpty || password.isEmpty {
            self.authError = "所有字段都不能为空"
            return
        }
        
        if password != confirmPassword {
            self.authError = "两次输入的密码不一致"
            return
        }
        
        // 模拟网络请求延迟
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            // 模拟注册成功
            let user = User(username: username, email: email)
            self.currentUser = user
            self.isAuthenticated = true
            self.authError = nil
            
            // 保存用户信息到UserDefaults
            self.saveUserToDefaults(user)
        }
    }
    
    func logout() {
        self.currentUser = nil
        self.isAuthenticated = false
        
        // 清除UserDefaults中的用户信息
        UserDefaults.standard.removeObject(forKey: userDefaultsKey)
    }
    
    private func saveUserToDefaults(_ user: User) {
        if let encoded = try? JSONEncoder().encode(user) {
            UserDefaults.standard.set(encoded, forKey: userDefaultsKey)
        }
    }
    
    private func loadUserFromDefaults() {
        if let userData = UserDefaults.standard.data(forKey: userDefaultsKey),
           let user = try? JSONDecoder().decode(User.self, from: userData) {
            self.currentUser = user
            self.isAuthenticated = true
        }
    }
}